package com.chatplus.application.common.util;

import cn.hutool.core.date.DateUtil;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtilsBean;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.converters.AbstractConverter;
import org.apache.commons.beanutils.converters.SqlTimestampConverter;

import java.time.Instant;
import java.util.Date;

public final class ConvertUtils {
    private static final ConvertUtilsBean convertUtils = BeanUtilsBean.getInstance().getConvertUtils();

    static {
        convertUtils.register(new InstantConverter(), Instant.class);
    }
    /**
     * 使用apache beanutils包提供的转换器转换值
     * @param value 要转换的值
     * @param targetType 目标类型
     * @param <T> 目标类型
     * @return 转换后的值
     */
    @SuppressWarnings("unchecked")
    public static <T> T convert(Object value, Class<T> targetType) {
        return (T) convertUtils.convert(value, targetType);
    }

    public static class InstantConverter extends AbstractConverter implements Converter {
        private final SqlTimestampConverter sqlTimestampConverter = new SqlTimestampConverter();

        @SuppressWarnings("unchecked")
        @Override
        protected <T> T convertToType(Class<T> type, Object value) throws Throwable {
            if (value instanceof Instant) {
                return (T) value;
            }
            Date date = sqlTimestampConverter.convert(Date.class, value);
            return (T) DateUtil.toInstant(date);
        }

        @Override
        protected Class<?> getDefaultType() {
            return Instant.class;
        }
    }
}
